package model

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"strings"
)

func CreateTables(sqlConn sqlx.SqlConn, dbType string) error {
	var createDatabaseSQL, createAlertRulesTableSQL, createNotificationConfigsTableSQL string

	switch strings.ToLower(dbType) {
	case "mysql":
		createDatabaseSQL = "CREATE DATABASE IF NOT EXISTS yunfan_bigdata DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;"

		createAlertRulesTableSQL = `
        CREATE TABLE IF NOT EXISTS yunfan_bigdata.alert_rules_info (
            id int NOT NULL AUTO_INCREMENT COMMENT '告警规则ID',
            component_name varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '服务类型，如 "host", "hadoop_logic", "kafka_logic", "zookeeper_logic"',
            component_role varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '服务角色，如 "namenode", "nodemanager", "broker"',
            metric varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '监控指标，如 "cpu", "memory", "disk", "node_count"',
            operator varchar(10) COLLATE utf8mb4_general_ci NOT NULL COMMENT '比较运算符，如 ">", "<", ">=", "<="',
            threshold float NOT NULL COMMENT '阈值，如 "100"',
            enabled BOOLEAN NOT NULL DEFAULT TRUE COMMENT '是否激活',
            notification_config JSON COMMENT '告警通知配置',
            description text COMMENT '告警描述',
            created_at timestamp(3) NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '创建时间',
            updated_at timestamp(3) NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT '更新时间',
            PRIMARY KEY (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='告警规则表，用于存储各种服务的告警规则';
        `

		createNotificationConfigsTableSQL = `
        CREATE TABLE IF NOT EXISTS yunfan_bigdata.notifications (
            id int NOT NULL AUTO_INCREMENT COMMENT '主键，唯一标识每一条通知配置',
            name varchar(255) NOT NULL COMMENT '名称',
            type enum('email','sms','dingtalk','weixin','webhook') NOT NULL COMMENT '通知方式，例如电子邮件、短信等',
            config json NOT NULL COMMENT '存储该通知方式的具体配置信息，如 SMTP 配置等',
            created_at timestamp(3) NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '记录创建时间',
            updated_at timestamp(3) NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT '记录更新时间',
            deleted_at timestamp(3) NULL DEFAULT NULL COMMENT '记录删除时间',
            PRIMARY KEY (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='存储各种通知方式的配置信息';
        `
	case "sqlite":
		createAlertRulesTableSQL = `
        CREATE TABLE IF NOT EXISTS alert_rules_info (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            component_name TEXT NOT NULL,
            component_role TEXT NOT NULL,
            metric TEXT NOT NULL,
            operator TEXT NOT NULL,
            threshold REAL NOT NULL,
            enabled BOOLEAN NOT NULL DEFAULT TRUE,
            notification_config TEXT,
            description TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now', 'localtime')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now', 'localtime'))
        );
        `

		createNotificationConfigsTableSQL = `
        CREATE TABLE IF NOT EXISTS notifications (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            type TEXT NOT NULL CHECK(type IN ('email','sms','dingtalk','weixin','webhook')),
            config TEXT NOT NULL,
            created_at TEXT NOT NULL DEFAULT (datetime('now', 'localtime')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now', 'localtime')),
            deleted_at TEXT
        );
        `
	default:
		return fmt.Errorf("unsupported database type: %s", dbType)
	}

	if dbType == "mysql" {
		// 创建数据库（仅 MySQL 需要）
		_, err := sqlConn.Exec(createDatabaseSQL)
		if err != nil {
			return fmt.Errorf("failed to create yunfan_bigdata database: %v", err)
		}
	}

	// 创建表
	tables := []string{
		createAlertRulesTableSQL,
		createNotificationConfigsTableSQL,
	}

	for _, tableSQL := range tables {
		_, err := sqlConn.Exec(tableSQL)
		if err != nil {
			return fmt.Errorf("failed to create table: %v", err)
		}
	}

	return nil
}
